package com.paul.mq.dependencies.mq.aliyun;


import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.paul.mq.bean.enums.PushWayEnum;
import com.paul.mq.config.AliyunMQConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by zmk523@163.com on 2019/6/29 13:12
 * 参考：https://blog.csdn.net/hzr0523/article/details/80263659
 */

@Configuration
@Component
public class RocketMqConfig {
    @Autowired
    private AliyunMQConfig aliyunMQConfig;

    private final RocketMQConsumer consumer;

    @Autowired
    public RocketMqConfig(RocketMQConsumer consumer) {
        this.consumer = consumer;
    }

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean normalConsumer() {
        ConsumerBean consumerBean = new ConsumerBean();
        Properties properties = buildTokenProperties();
        properties.put(PropertyKeyConst.GROUP_ID, aliyunMQConfig.getAliyunMQGroupId());
        consumerBean.setProperties(properties);
        //绑定监听的topic
        Subscription subscription = new Subscription();
        subscription.setTopic(aliyunMQConfig.getAliyunMQTopic());
        //绑定要监听的tag，多个tag用 || 隔开
        subscription.setExpression(PushWayEnum.allTag());
        Map<Subscription, MessageListener> map = new HashMap();
        map.put(subscription, consumer);
        consumerBean.setSubscriptionTable(map);
        return consumerBean;
    }

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ProducerBean normalProducer() {
        ProducerBean producer = new ProducerBean();
        Properties properties = buildTokenProperties();
        properties.put(PropertyKeyConst.GROUP_ID, aliyunMQConfig.getAliyunMQGroupId());
        properties.put(PropertyKeyConst.NAMESRV_ADDR,aliyunMQConfig.getAliyunMQNameSrvAddr());
        producer.setProperties(properties);
        return producer;
    }

    private Properties buildTokenProperties() {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.AccessKey, aliyunMQConfig.getAliyunAccessKey());
        properties.put(PropertyKeyConst.SecretKey, aliyunMQConfig.getAliyunSecretKey());
        //配置对应 Group ID 的最大消息重试次数为 20 次
//        properties.put(PropertyKeyConst.MaxReconsumeTimes,"20");
        return properties;
    }

}